<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

class m_website_actions_block_WebsiteEditAction extends m_backoffice_extends_Action
{
	public function execute()
	{
		$documentId = $this->getRequestParameter('docId');
		$documentLang = $this->getRequestParameter('docLang');
		
		$website = f_document_Provider::getInstance()->getByModelAndUniqueId('website/Website', $documentId, $documentLang);
		$this->addToModel('websiteLabel', $website->getLabel());
		$values = $this->getFormValues('form');

        $this->addToModel('themes', m_website_services_WebsiteService::getInstance()->getFrontThemes());

        // to avoid notices
        $this->addToModel("errors", array('status' => null, 'url' => null, 'label' => null));

		if(count($values) > 0)
		{
			$errors = $this->checkForm($values, $website);

			$website->setAuthor($this->getUser()->getLogin())
					->setLabel($values['label'])
					->setUrl($values['url'])
                    ->setTheme($values['theme']);

            if(isset($values['displayLang']))
            {
                $website->setDisplayLang($values['displayLang']);
            }

			if(count($errors) == 0)
			{
				$website->save();				
			}
			else
			{
				$errors['status'] = 'failed';
				$this->addToModel('errors', $errors);
			}			
		}

        $this->addToModel('frontLang', $this->getCultureLabel($website->getDisplayLang()));
		$this->addToModel('frontLangs', f_locale_Manager::getIsoCodes());
		$this->addToModel('website', $website);
		
		$this->setView('success');
	}	
	
	public function validate()
	{
		return $this->getUserContext()->hasRight(array("backoffice_accessBo", "website_Properties"));
	}
	
	public function checkForm($formValues, $website)
	{
		$errors = array();
			
		if($formValues["url"] == "" && !$website->isATranslation())
		{
			$errors["url"] = $this->getLocale('website.errors.required');
		}
		
		if($formValues["label"] == "")
		{
			$errors["label"] = $this->getLocale('website.errors.required');
		}

        if($this->checkIfUrlExists($formValues["url"], $website->getUniqueId()))
		{
			$errors["url"] = $this->getLocale('website.errors.duplicateURL');
		}
				
		return $errors;
	}

	private function checkIfUrlExists($url, $currentId)
	{
		$dbProvider = f_database_Provider::getInstance();

		$sql = "SELECT `document_uid` FROM `m_website__website` WHERE `url`=:url AND `document_uid`!=:id";

		return count($dbProvider->setQuery($sql)->execute(array("url" => $url, "id" => $currentId))->getQueryResults(PDO::FETCH_COLUMN)) >= 1;
	}
}